import Router from '@koa/router';
import db from '../mysqlHelper.js';
import logger from '../logger.js';
import response from '../response.js';
import md5 from 'md5';
import moment from 'moment';
import { createToken } from '../auth.js';


const router = new Router;
router.prefix('/api');


router.post('/oper/login', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    let joinParam =
        [
            {
                fields: 'oper.*,role.role_name,role.role_value',
                table: 'role',
                on: 'oper.role_id=role.id'
            }
        ]

    let { count, rows } = await db.findAll('oper', { account: body.account }, null, 'desc', 1, 0, null, null, joinParam);
    if (count == 0) {
        ctx.body = response.fail("帐号不存在");
        return;
    }
    let oper = rows[0];
    if (oper.password == null) oper.password = '';
    if (oper.password == '' || oper.password == md5(body.password)) {
        const { token, expireTime } = await createToken({ account: oper.account, role_id: oper.role_id });
        oper.token = token;
        oper.expireTime = expireTime;
        delete oper.password;
        ctx.body = response.success(oper);
        return;
    }
    else {
        ctx.body = response.fail("密码错误");
    }
});



router.post('/op/insert', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let isExist = await db.findOne('oper', { account: body.account });
    if (isExist != null) {
        ctx.body = response.fail("相同帐号已存在");
        return;
    }
    if (body.password != null) {
        body.password = md5(body.password);
    }
    let res = await db.create('oper', body);
    if (res instanceof Error) {
        logger.error(`oper create error :` + res.message);
        ctx.body = response.fail(`oper create error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/op/update', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    let obj = await db.findOne('oper', { account: body.account })
    if (obj == null) {
        ctx.body = response.fail("要修改数据不存在");
        return;
    }
    for (let key in body) {
        if (body[key] != undefined) {
            if (key == 'pass') {
                obj[key] = md5(body[key]);
            }
            else {
                obj[key] = body[key];
            }
        }
    }
    let res = await db.update('oper', obj, { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper update error :` + res.message);
        ctx.body = response.fail(`oper update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/op/remove', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    let res = await db.deleteRow('oper', { account: body.account });
    if (res instanceof Error) {
        logger.error(`oper delete error :` + res.message);
        ctx.body = response.fail(`oper delete error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/op/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' }
    }
    else {
        if (!body.direction) body.direction = 'desc';
    }
    let res = await db.findAll('oper', body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr);
    if (res instanceof Error) {
        logger.error(`oper getList error :` + res.message);
        ctx.body = response.fail(`oper getList error :` + res.message);
        return;
    }
    ctx.body = response.success({ rows: res.rows, count: res.count });
});

router.post('/oper/changePass', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    if (body.account == null) {
        ctx.body = response.fail("缺少必填字段 帐号");
        return;
    }
    if (body.oldPass == null) {
        ctx.body = response.fail("缺少必填字段 旧密码");
        return;
    }
    if (body.newPass == null) {
        ctx.body = response.fail("缺少必填字段 新密码");
        return;
    }
    let oper = await db.findOne('oper', { account: body.account });
    if (oper == null) {
        ctx.body = response.fail("帐号不存在");
        return;
    }
    if (oper.password == '' || oper.password == md5(body.oldPass)||oper.password==null) {
   
            oper.password = md5(body.newPass);
            let res =await db.update('oper', oper, { account: body.account });
            if (res instanceof Error) {
                logger.error(`oper update error :` + res.message);
                ctx.body = response.fail(`change password update error :` + res.message);
                return;
            }
            ctx.body = response.success();
        
    } else {
        ctx.body = response.fail("旧密码错误");
    }
});


router.post('/:table/insert', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let isExist = false;
    switch (ctx.params.table) {
        case 'role':
            if (body.role_name == null) {
                ctx.body = response.fail("缺少必填字段 角色名称");
                return;
            }
            if (body.role_value == null) {
                ctx.body = response.fail("缺少必填字段 角色值");
                return;
            }
            isExist = await db.checkExist('role', { role_name: body.role_name });
            if (isExist) {
                ctx.body = response.fail("相同角色已存在");
                return;
            }
            break;
        case 'enterprise':
            if (body.name == null) {
                ctx.body = response.fail("缺少必填字段 企业名称");
                return;
            }
            isExist = await db.checkExist('enterprise', { name: body.name });
            if (isExist) {
                ctx.body = response.fail("相同企业已存在");
                return;
            }
            break;
        case 'project':
            if (body.id == null) {
                ctx.body = response.fail("缺少必填字段 企业id");
                return;
            }
            if (body.project_name == null) {
                ctx.body = response.fail("缺少必填字段 项目名称");
                return;
            }
            // isExist = await db.checkExist('project', { name: body.id });
            // if (isExist) {
            //     ctx.body = response.fail("相同项目已存在");
            //     return;
            // }
            break;
        case 'project_cfg':
            if (body.id == null) {
                ctx.body = response.fail("缺少必填字段 项目id");
                return;
            }
            if (body.cfg == null) {
                ctx.body = response.fail("缺少必填字段 配置内容");
                return;
            }
        case  'device':
            if(body.sn==null){
                ctx.body = response.fail("缺少必填字段 sn");
                return;
            }
            if(body.model==null){
                ctx.body = response.fail("缺少必填字段 model");
                return;
            }
            if(body.name==null){
                ctx.body = response.fail("缺少必填字段 name");
                return;
            }
        case  'camera':
            if(body.sn==null){
                ctx.body = response.fail("缺少必填字段 sn");
                return;
            }
            if(body.project_id==null){
                ctx.body = response.fail("缺少必填字段 project_id");
                return;
            }
            if(body.name==null){
                ctx.body = response.fail("缺少必填字段 name");
                return;
            }
        case `svg_list`:
            if(body.id==null){
                ctx.body = response.fail("缺少必填字段 id");
                return;
            }
            if(body.diagram_id==null){
                ctx.body = response.fail("缺少必填字段 diagram_id");
                return;
            }
            if(body.svg_file==null){
                ctx.body = response.fail("缺少必填字段 svg_file");
                return;
            }
            if(body.project_id==null){
                ctx.body = response.fail("缺少必填字段 project_id");
                return;
            }
        case 'device_bind':
            if(body.id==null){
                ctx.body = response.fail("缺少必填字段 id");
                return;
            }
            if(body.device_sn==null){
                ctx.body = response.fail("缺少必填字段 device_sn");
                return;
            }
            if(body.pel_id==null){
                ctx.body = response.fail("缺少必填字段 pel_id");
                return;
            }
            
        default:
    }

    let res = await db.create(ctx.params.table, body);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} create error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} create error :` + res.message);
        return;
    }
    if(ctx.params.table=='device'){
        memDB.setDevice({sn:body.sn,model:body.model});
    }
    ctx.body = response.success({ id: res.insertId });
});

function getConditions(tbaleName, body) {
    let conditions = {};
    switch (tbaleName) {
        case 'role':
            if (body.id == null) {
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };
        case 'enterprise':
            if (body.id == null) {
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };
        case 'project':
            if (body.id == null) {
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };
        case 'project_cfg':
            if (body.id == null) {
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };
        case 'device':
            if(body.sn==null){
                return { code: 0, conditions, msg: "缺少必填字段 sn" };
            }
            conditions = { sn: body.sn }
            return { code: 1, conditions: conditions };
        case 'camera':
            if(body.sn==null){
                return { code: 0, conditions, msg: "缺少必填字段 sn" };
            }
            conditions = { sn: body.sn }
            return { code: 1, conditions: conditions };
        case `svg_list`:
            if(body.id==null){
                return { code: 0, conditions, msg: "缺少必填字段 id" };
            }
            conditions = { id: body.id }
            return { code: 1, conditions: conditions };
        case 'device_bind':
            if(body.sn==null){
                return { code: 0, conditions, msg: "缺少必填字段 sn" };
            }
            conditions = { sn: body.sn }
            return { code: 1, conditions: conditions };
        default:
    }
}

router.post('/:table/update', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions
    let obj = await db.findOne(ctx.params.table, conditions)
    if (obj == null) {
        ctx.body = response.fail("要修改数据不存在");
        return;
    }
    for (let key in body) {
        if (body[key] != undefined && body[key] != null) {
            obj[key] = body[key];
        }
    }
    res = await db.update(ctx.params.table, obj, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} update error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} update error :` + res.message);
        return;
    }
    ctx.body = response.success();
});

router.post('/:table/remove', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail("参数不允许为空");
        return;
    }
    let res = getConditions(ctx.params.table, body);
    if (res.code == 0) {
        ctx.body = response.fail(res.msg);
        return;
    }
    let conditions = res.conditions
    res = await db.deleteRow(ctx.params.table, conditions);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} delete error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} delete error :` + res.message);
        return;
    }
    if(ctx.params.table=='device'){
        memDB.deleteDevice({sn:body.sn});
    }
    ctx.body = response.success();
});
router.post('/:table/getList', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        body = { limit: 10, offset: 0, direction: 'desc' }
    }
    else {
        if (!body.direction) body.direction = 'desc';
    }
    let res = await db.findAll(ctx.params.table, body.conditions, body.orderBy, body.direction, body.limit, body.offset, body.areaArr, body.likeArr, body.leftJoinArr, body.inArr);
    if (res instanceof Error) {
        logger.error(`${ctx.params.table} getList error :` + res.message);
        ctx.body = response.fail(`${ctx.params.table} getList error :` + res.message);
        return;
    }
    ctx.body = response.success({ rows: res.rows, count: res.count });
});



export { router };